﻿using LuckyFish.ToDo.Data.Model;
using Microsoft.EntityFrameworkCore;

namespace LuckyFish.ToDo.Data;

public sealed class ToDoContext : DbContext
{
    public DbSet<ToDoGroupModel> Groups { get; set; }
    public DbSet<ToDoModel> ToDos { get; set; }
    public DbSet<StepModel> Steps { get; set; }

    public ToDoContext()
    {
        try
        {
            Database.Migrate();
        }
        catch
        {
            Database.EnsureCreated();
        }
    }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite("Data Source=Data.db");

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ToDoModel>()
            .HasOne(x => x.Group)
            .WithMany(x => x.ToDos)
            .HasForeignKey(x => x.GroupKey)
            .IsRequired(false)
            .OnDelete(DeleteBehavior.Cascade);

        modelBuilder.Entity<StepModel>()
            .HasOne(x => x.ToDo)
            .WithMany(x => x.Steps)
            .HasForeignKey(x => x.ToDoKey)
            .OnDelete(DeleteBehavior.Cascade);
    }
}